/**
 * Created by yerdos on 2015/9/10.
 */


app.factory('apiHelper', ['$http', '$q', '$rootScope', function ($http, $q, $rootScope) {

  var success = function(resp){
    if (!resp.data.hasError) {
      return resp.data;
    } else if(resp.data.hasError || !resp.data.errorMessage){
      $rootScope.toaster.error("操作提示", "失败：" + resp.data.errorMessage);
      return false;
    }
  };

  var error = function(resp){
    if(resp.status === 0){
      $rootScope.toaster.error("操作提示", "服务错误[" + resp.status + "]，请与管理员联系！" );
    }
    else if(resp.status === 404){
      $rootScope.toaster.error("操作提示", "服务错误[" + resp.status + "]，请求的资源不存在！" );
    }
    else if(resp.message == 'Unexpected token h') { //401，没有授权。TODO: 因为无法获取status的值，所以只能暂时这么处理。
      $rootScope.$state.go('login');
    }

    return false;
  };

  return {
    callService: function (url, method, params, data) {
      if(params){
        params._rand = Math.random();
      }
      return $http({
        url: url,
        method: method,
        params: (method != 'POST' && !!params) ? { parameters: JSON.stringify(params || {_rand : Math.random()}) } : null,
        data: data
        //headers:{
        //  'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
        //}
      })
        .then(success, error);
    },

    deferCallService: function (url, method, params, data) {
      var deferred = $q.defer();

      $http({
        url: url,
        method: method,
        params: params,
        data: data
      }).then(function (resp) {
        if (!resp.data.HasError) {
          deferred.resolve(resp.data.Data);
        } else {
          deferred.reject(resp.data.Error);
        }
      });

      return deferred.promise;
    }
  }
}]);
